#!/bin/bash

# 增强版rclone安装脚本
# 支持多种Linux发行版和架构

set -e

echo "开始增强版rclone安装..."

# 检查是否以root权限运行
if [[ $EUID -eq 0 ]]; then
    echo "以root用户运行"
    USE_SUDO=""
else
    echo "以普通用户运行"
    if command -v sudo &> /dev/null; then
        USE_SUDO="sudo"
    else
        echo "警告: 未找到sudo命令"
        USE_SUDO=""
    fi
fi

# 检查系统架构
ARCH=$(uname -m)
echo "系统架构: $ARCH"

# 根据架构确定正确的下载URL
case $ARCH in
    x86_64)
        RCLONE_ARCH="amd64"
        ;;
    aarch64|arm64)
        RCLONE_ARCH="arm64"
        ;;
    armv7l)
        RCLONE_ARCH="arm-v7"
        ;;
    i386|i686)
        RCLONE_ARCH="386"
        ;;
    *)
        echo "警告: 未知架构 $ARCH，使用amd64作为默认值"
        RCLONE_ARCH="amd64"
        ;;
esac

echo "使用架构: $RCLONE_ARCH"

# 检查系统类型
if [ -f /etc/os-release ]; then
    . /etc/os-release
    OS=$NAME
    VER=$VERSION_ID
    echo "操作系统: $OS $VER"
else
    echo "无法确定操作系统类型"
fi

# 下载并安装rclone
echo "下载rclone..."
DOWNLOAD_URL="https://downloads.rclone.org/rclone-current-linux-$RCLONE_ARCH.zip"

# 尝试使用curl下载
if command -v curl &> /dev/null; then
    echo "使用curl下载..."
    curl -L -o rclone-current-linux-$RCLONE_ARCH.zip $DOWNLOAD_URL
elif command -v wget &> /dev/null; then
    echo "使用wget下载..."
    wget -O rclone-current-linux-$RCLONE_ARCH.zip $DOWNLOAD_URL
else
    echo "错误: 未找到curl或wget命令，请先安装其中一个"
    exit 1
fi

# 检查下载是否成功
if [ ! -f "rclone-current-linux-$RCLONE_ARCH.zip" ]; then
    echo "错误: 下载失败"
    exit 1
fi

# 解压文件
echo "解压文件..."
unzip -q rclone-current-linux-$RCLONE_ARCH.zip

# 获取解压后的目录名
RCLONE_DIR=$(ls -d rclone-*-linux-$RCLONE_ARCH 2>/dev/null | head -n 1)

if [ -z "$RCLONE_DIR" ]; then
    echo "错误: 无法找到解压后的rclone目录"
    exit 1
fi

echo "找到目录: $RCLONE_DIR"

# 进入目录
cd $RCLONE_DIR

# 复制二进制文件到系统路径
echo "安装rclone..."
$USE_SUDO cp rclone /usr/local/bin/
$USE_SUDO chown root:root /usr/local/bin/rclone
$USE_SUDO chmod 755 /usr/local/bin/rclone

# 安装man页面（如果存在）
if [ -f "rclone.1" ]; then
    $USE_SUDO mkdir -p /usr/local/share/man/man1
    $USE_SUDO cp rclone.1 /usr/local/share/man/man1/
    $USE_SUDO mandb 2>/dev/null || echo "无法更新man数据库"
fi

# 创建配置目录
mkdir -p ~/.config/rclone

# 返回上级目录
cd ..

# 清理临时文件
echo "清理临时文件..."
rm -rf rclone-current-linux-$RCLONE_ARCH.zip $RCLONE_DIR

# 验证安装
echo "验证安装..."
if command -v rclone &> /dev/null; then
    VERSION_OUTPUT=$(rclone --version 2>&1)
    if [ $? -eq 0 ]; then
        echo "rclone安装成功!"
        echo "$VERSION_OUTPUT"
        exit 0
    else
        echo "错误: rclone命令存在但无法执行"
        exit 1
    fi
else
    echo "错误: rclone安装失败，命令未找到"
    exit 1
fi